import cv2
import numpy as np
from utils.common import load_image, show_image, make_dirs
from utils.config import exp5_sift_path, exp5_output_dir


def main():
    try:
        # 确保输出目录存在
        make_dirs(exp5_output_dir)

        # 加载图片
        image = load_image()
        if image is None:
            raise ValueError("无法加载图片，请检查路径是否正确")

        # 灰度化
        gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # 初始化SIFT检测器（兼容不同OpenCV版本）
        try:
            sift = cv2.SIFT_create()  # OpenCV >= 4.4.0
        except AttributeError:
            try:
                sift = cv2.xfeatures2d.SIFT_create()  # OpenCV 3.x
            except AttributeError:
                raise ImportError("您的OpenCV版本不支持SIFT算法")

        # 检测关键点和描述符
        keypoints, descriptors = sift.detectAndCompute(gray_image, None)

        if not keypoints:
            print("警告：未检测到任何关键点")
            return

        # 绘制关键点（使用原图效果更好）
        img_with_keypoints = cv2.drawKeypoints(
            image,  # 使用原图而不是灰度图
            keypoints,
            None,
            flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS
        )

        # 显示结果
        show_image("SIFT Keypoints", img_with_keypoints)

        # 保存结果
        cv2.imwrite(exp5_sift_path, img_with_keypoints)
        print(f"检测到 {len(keypoints)} 个关键点")
        print(f"SIFT结果已保存到：{exp5_sift_path}")

        # 可选：保存描述符
        # np.save(exp5_sift_path.replace('.jpg', '_descriptors.npy'), descriptors)

    except Exception as e:
        print(f"程序执行出错: {str(e)}")


if __name__ == "__main__":
    main()